package com.mzj.saas.mservice.member.service;

import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.department.entity.CustomFieldManagement;
import com.mzj.saas.mservice.department.entity.CustomFieldValue;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.entity.UserDepartmentRef;
import com.mzj.saas.mservice.department.repository.CustomFieldManagementRepository;
import com.mzj.saas.mservice.department.repository.CustomFieldValueRepository;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.department.repository.UserDepartmentRefRepository;
import com.mzj.saas.mservice.department.service.DepartmentService;
import com.mzj.saas.mservice.roles.entity.Role;
import com.mzj.saas.mservice.roles.entity.UserRoleRef;
import com.mzj.saas.mservice.roles.repository.RoleRepository;
import com.mzj.saas.mservice.roles.repository.UserRoleRefRepository;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class MemberService {
    private static final Logger LOG = LoggerFactory.getLogger(MemberService.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private CustomFieldManagementRepository customFieldManagementRepository;
    @Autowired
    private CustomFieldValueRepository customFieldValueRepository;
    @Autowired
    private UserRoleRefRepository userRoleRefRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private UserDepartmentRefRepository userDepartmentRefRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private DepartmentService departmentService;

    /*
     *人员管理-显示人员列表
     */
    public ResultBean<Object> peopleManagerList(String accessToken, Integer pageNumber, Integer pageSize) {
        LOG.info("---MemberService peopleManagerList accessToken={},pageNumber={},pageSize={}", accessToken, pageNumber, pageSize);
        ResultBean<Object> result = new ResultBean<>();
        ApiData<Map<String, Object>> apiData = new ApiData<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        try {
            if (tokenRedisVo == null) {
                result.setCode(StatusCode.ERROR_CODE_40001.getErrorCode());
                result.setMsg(StatusCode.ERROR_CODE_40001.getErrorMsg());
                return result;
            }

            User existUser = userRepository.findById(tokenRedisVo.getId());
            if (existUser == null) {
                return ResultBean.failedResultWithMsg("用户信息不存在或已删除");
            }

            List<Long> allDepIds = new ArrayList<>();
            if (tokenRedisVo.getMasterStatus() == 1) {
                allDepIds.addAll(departmentService.findHierarchyAll(tokenRedisVo.getEnterpriseId()));
            } else {
                List<UserDepartmentRef> userDepartmentRefList = userDepartmentRefRepository.findByUserId(existUser.getId());
                for (UserDepartmentRef userDepartmentRef : userDepartmentRefList) {
                    allDepIds.add(userDepartmentRef.getDepId());
                }
            }

            List<Department> departmentList = departmentRepository.findByIdIn(allDepIds);
            if (departmentList == null || departmentList != null && departmentList.size() <= 0) {
                return ResultBean.failedResultWithMsg("部门不存在或已删除");
            }

            //所有权限部门及其子集部门id
            List<Long> depIds = new ArrayList<>();
            depIds.addAll(allDepIds);
            for (Long depId : allDepIds) {
                depIds.addAll(departmentService.allChild(depId));
            }
            depIds = depIds.stream().distinct().collect(Collectors.toList());

            StringBuffer depIdStringBuffer = new StringBuffer();
            String depId = "";
            if (depIds != null && depIds.size() > 0) {
                for (Long id : depIds) {
                    depIdStringBuffer.append(id).append(",");
                }
                depId = depIdStringBuffer.substring(0, depIdStringBuffer.lastIndexOf(","));
            }

            StringBuffer sbSql = new StringBuffer(" SELECT u.id,u.`name`,u.`mobile`,u.position,u.job_number AS jobNumber,u.`entry_time` AS entryTime,u.`create_time` AS createTime,u.email FROM `saas_user` u WHERE u.status != 2");
            if (StringUtils.isNotBlank(depId)) {
                sbSql.append(" AND id IN (SELECT DISTINCT `user_id` FROM `saas_user_department_ref` WHERE `dep_id` IN (" + depId + "))");
            }

            // 查询总记录数
            StringBuffer count = new StringBuffer("SELECT COUNT(0) FROM  (" + sbSql + ")  c");
            Long total = jdbcTemplate.queryForObject(count.toString(), Long.class);
            if (total == 0) {
                result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
                result.setResultData(null);
                return result;
            }

            // 查询分页数据
            String offsets = "  LIMIT ? OFFSET ? ";
            List<Object> args = new ArrayList<>();
            sbSql.append(offsets);
            args.add(pageSize);
            args.add(pageNumber * pageSize);

            List<Long> allChild = departmentService.allChild(tokenRedisVo.getEnterpriseId());

            List<Map<String, Object>> peopleList = jdbcTemplate.queryForList(sbSql.toString(), args.toArray());
            for (Map<String, Object> m : peopleList) {
                String id = String.valueOf(m.get("id"));
                //部门
                List<UserDepartmentRef> userDepartment = userDepartmentRefRepository.findByUserId(id);
                List<Long> userDepIds = new ArrayList<>();
                List<String> depNames = new ArrayList<>();
                for (UserDepartmentRef userDepartmentRef : userDepartment) {
                    Optional<Department> existDepartment = departmentRepository.findById(userDepartmentRef.getDepId());
                    if (existDepartment.isPresent()) {
                        Department department = existDepartment.get();
                        userDepIds.add(userDepartmentRef.getDepId());
                        depNames.add(department.getName());
                    }
                }
                m.put("depId", userDepIds);
                m.put("depNames", depNames);

                if (userDepIds.contains(tokenRedisVo.getEnterpriseId())) {
                    // currentCompany: 1 当前企业 ,0 不是当前企业
                    m.put("currentCompany", 1);
                } else {
                    m.put("currentCompany", 0);
                }
                // 如果是当前企业的下级部门,也设置为1
                for (Long child : allChild) {
                    if (userDepIds.contains(child)) {
                        m.put("currentCompany", 1);
                    }
                }

                List<CustomFieldValue> customFieldValue = customFieldValueRepository.findByUserId(id);
                customFieldValue.forEach(c -> {
                    String fieldValue = c.getFieldValue();
                    Long fieldId = c.getFieldId();
                    Optional<CustomFieldManagement> customFieldManagementOptional = customFieldManagementRepository.findById(fieldId);
                    if (customFieldManagementOptional.isPresent()) {
                        CustomFieldManagement customFieldManagement = customFieldManagementOptional.get();
                        String fieldName = customFieldManagement.getFieldName();
                        m.put(fieldName, fieldValue);
                    }
                });

                //角色
                List<UserRoleRef> userRoleRefs = userRoleRefRepository.findByUserId(id);
                List<Long> roleIds = new ArrayList<>();
                List<String> roleNames = new ArrayList<>();
                Integer isMaster = 0;//是否主管理员：0否，1是
                for (UserRoleRef userRoleRef : userRoleRefs) {
                    Role userRole = roleRepository.findByIdAndProperty(userRoleRef.getRoleId(), 2);
                    if (userRole != null) {
                        roleIds.add(userRole.getId());
                        roleNames.add(userRole.getName());
                        if (userRole.getType() == 1) {
                            isMaster = 1;
                        }
                    }
                }
                m.put("role", roleIds);
                m.put("roleNames", roleNames);
                m.put("isMaster", isMaster);
            }

            apiData.setData(peopleList);
            apiData.setTotal(total);
            result.setResultData(apiData);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }


}
